package ar.republicagroup.gestion.view;

import ar.republicagroup.gestion.entities.BolsaCheque;
import ar.republicagroup.gestion.entities.Cheque;
import ar.republicagroup.gestion.entities.Cliente;
import ar.republicagroup.gestion.entities.Usuario;
import ar.republicagroup.gestion.services.BolsaChequeServices;
import ar.republicagroup.gestion.services.ChequeServices;
import ar.republicagroup.gestion.services.ClienteServices;
import ar.republicagroup.gestion.util.JComboBoxModel;
import ar.republicagroup.gestion.util.SpringUtils;
import ar.republicagroup.gestion.util.TableColumnAdjuster;
import ar.republicagroup.gestion.util.UserSession;
import ar.republicagroup.gestion.util.helpers.Formato;
import ar.republicagroup.gestion.util.messages.UIMessages;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.apache.log4j.Logger;

/**
 *
 * @author DIEGOALV
 */
public class modalPanelEditBolsaAndCheque extends javax.swing.JDialog {

    ClienteServices clienteServices                 = (ClienteServices)SpringUtils.getBean("clienteServices");
    ChequeServices  chequeServices                  = (ChequeServices)SpringUtils.getBean("chequeServices");
    BolsaChequeServices  bolsaChequeServices        = (BolsaChequeServices)SpringUtils.getBean("bolsaChequeServices");
    private static Logger log                       = Logger.getLogger(modalPanelEditBolsaAndCheque.class);
    
    private List<Cheque> chequeList;
    
    
    public modalPanelEditBolsaAndCheque(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        cargarCombos();
        valoresPorDefecto();
    }

    private void cargarCombos(){
        comboCliente.setModel(clienteServices.combo());
    }
    
    private void valoresPorDefecto(){
        panelBolsa.setVisible(false);
        rbtBolsaNueva.setSelected(true);
        
    }
    
    public void cargarTablaCheque(List<Cheque> chequeList){
    
        DefaultTableModel model = (DefaultTableModel) tblCheque.getModel();
        model.getDataVector().clear();
        tblCheque.clearSelection();
       
        for(Cheque cheque : chequeList){
          model.addRow(new Object[]{cheque.getBolsaChequeId().getId(),cheque.getChequeTipoId().getTipo(),cheque,Formato.fechaDDMMYY(cheque.getFechaAlta()),cheque.getBolsaChequeId().getClienteId().getNombre(),cheque.getBancoId().getNombre(),cheque.getOrigen(),Formato.decimalComaMilesConSigno(cheque.getImporte().floatValue()),cheque.getComision().floatValue()});
        }  
    
        TableColumnAdjuster tca = new TableColumnAdjuster(tblCheque);
        tca.adjustColumns();
        tblCheque.setModel(model);
        tblCheque.repaint();
        
    }
    
    
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblCheque = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        rbtBolsaNueva = new javax.swing.JRadioButton();
        rbtBolsaExistente = new javax.swing.JRadioButton();
        comboCliente = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        calendarFechaAlta = new com.toedter.calendar.JDateChooser();
        jLabel2 = new javax.swing.JLabel();
        btnAplicarCambio = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        panelBolsa = new javax.swing.JPanel();
        jComboBox1 = new javax.swing.JComboBox();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("...: Cambio de cliente :...");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Cheques seleccionados"));

        tblCheque.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Bolsa", "Tipo", "Cheque Nro", "Fecha alta", "Cliente", "Banco", "Origen", "Importe", "Comisión"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblCheque.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jScrollPane1.setViewportView(tblCheque);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 566, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Cambiar al cliente"));

        buttonGroup1.add(rbtBolsaNueva);
        rbtBolsaNueva.setText("Crear una bolsa nueva");

        buttonGroup1.add(rbtBolsaExistente);
        rbtBolsaExistente.setText("Pasarlos a una existente");

        jLabel1.setText("Cliente:");

        jLabel2.setText("Fecha alta:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(rbtBolsaNueva)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rbtBolsaExistente))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(comboCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(calendarFechaAlta, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(45, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rbtBolsaNueva)
                    .addComponent(rbtBolsaExistente))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(calendarFechaAlta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnAplicarCambio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/check.png"))); // NOI18N
        btnAplicarCambio.setText("Aplicar cambio");
        btnAplicarCambio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAplicarCambioActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        panelBolsa.setBorder(javax.swing.BorderFactory.createTitledBorder("Seleccione bolsa"));

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/search.png"))); // NOI18N
        jButton3.setText("Ver");

        javax.swing.GroupLayout panelBolsaLayout = new javax.swing.GroupLayout(panelBolsa);
        panelBolsa.setLayout(panelBolsaLayout);
        panelBolsaLayout.setHorizontalGroup(
            panelBolsaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBolsaLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton3)
                .addContainerGap())
        );
        panelBolsaLayout.setVerticalGroup(
            panelBolsaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBolsaLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelBolsaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3))
                .addContainerGap(58, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(panelBolsa, javax.swing.GroupLayout.DEFAULT_SIZE, 0, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(191, 191, 191)
                        .addComponent(btnAplicarCambio)
                        .addGap(27, 27, 27)
                        .addComponent(btnCancelar)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAplicarCambio, btnCancelar});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(panelBolsa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAplicarCambio)
                    .addComponent(btnCancelar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
          cargarTablaCheque(chequeList);
    }//GEN-LAST:event_formWindowOpened

    private void btnAplicarCambioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAplicarCambioActionPerformed
      if(comboCliente.getSelectedIndex() > 0){
            JComboBoxModel comboItem = (JComboBoxModel)comboCliente.getSelectedItem();   
            int respuesta = JOptionPane.showConfirmDialog(this, "¿Confirma el cambio de cliente a "+comboItem.getLabel()+"?", "Confirme", JOptionPane.YES_NO_OPTION);
            
            Cliente cliente = clienteServices.get(Integer.parseInt(comboItem.getValue()));
            
            if(respuesta == JOptionPane.YES_OPTION){
                BolsaCheque bolsaNueva = new BolsaCheque();
                bolsaNueva.setClienteId(cliente);
                bolsaNueva.setFechaAlta(calendarFechaAlta.getDate());
                bolsaNueva.setUsuarioId(new Usuario(UserSession.getInstance().getUser_id()));
                bolsaNueva.setEstado(1);
                
                List<Integer> chequeIdsToDelete = chequeServices.obtenerIdsFromChequeList(chequeList);
                
                for(Integer id : chequeIdsToDelete){
                   System.out.println("id to delete "+id); 
                   chequeServices.delete(id.intValue());
                }
                
                
                List<Cheque> chequeListUpdated = chequeServices.cambiarDeFechaAltaAndComision(chequeList,cliente , calendarFechaAlta.getDate());
                bolsaNueva.setChequeList(chequeListUpdated);
                String mensaje = bolsaChequeServices.insert(bolsaNueva);
                
                
                
                
                if(mensaje != null){
                    JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("onCompleteUpdate"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
                }else{
                    JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("onUpdateError"), UIMessages.getErrorMessage("onDeleteError"), JOptionPane.INFORMATION_MESSAGE);
                }
                
            }
            
            
      } else {
            JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("requiredSelectedCliente"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.ERROR_MESSAGE);
      }
        
    }//GEN-LAST:event_btnAplicarCambioActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    
    public List<Cheque> getChequeList() {
        return chequeList;
    }

    public void setChequeList(List<Cheque> chequeList) {
        this.chequeList = chequeList;
    }
    
    
    
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(modalPanelEditBolsaAndCheque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(modalPanelEditBolsaAndCheque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(modalPanelEditBolsaAndCheque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(modalPanelEditBolsaAndCheque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                modalPanelEditBolsaAndCheque dialog = new modalPanelEditBolsaAndCheque(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAplicarCambio;
    private javax.swing.JButton btnCancelar;
    private javax.swing.ButtonGroup buttonGroup1;
    private com.toedter.calendar.JDateChooser calendarFechaAlta;
    private javax.swing.JComboBox comboCliente;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel panelBolsa;
    private javax.swing.JRadioButton rbtBolsaExistente;
    private javax.swing.JRadioButton rbtBolsaNueva;
    private javax.swing.JTable tblCheque;
    // End of variables declaration//GEN-END:variables

   
}
